package com.dangf.launcher.server.pulgin.machine

import com.alibaba.fastjson.JSONObject
import com.dangf.launcher.server.httpserver.BaseDao
import org.litepal.crud.DataSupport

/**
 * Created by hais1992 on 2017/9/29.
 */
object MachineDao : BaseDao() {

    //注册机器
    fun registerMachine(machine: Machine): Machine {
        machine.save()
        return machine
    }

    //根据ID获取机器信息
    fun findMachineByCode(code: String): Machine? {
        try {
            return DataSupport.where("code = '$code' ").find(Machine::class.java).last()
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    //处理Api请求
    fun doApi(a: String, data: Map<String, String>): String {
        when (a) {
            "register" -> {
                val machineNew = JSONObject.parseObject(decode(data["machine"]), Machine::class.java)
                val machine = findMachineByCode(machineNew.code)
                if (machine == null) {
                    registerMachine(machineNew)
                    return getJson(100, "注册成功！", machine)
                } else {
                    return getJson(110, "机器已存在，不能重新注册！", null)
                }
            }
            "info" -> {
                val machine = findMachineByCode(data["code"]!!)
                if (machine == null) {
                    return getJson(110, "机器不存在！", null)
                } else {
                    return getJson(100, "", machine)
                }
            }
            else -> return getJson(404, "接口不存在！", null)
        }
        return ""
    }
}